﻿#include "stdafx.h"

#include "svgpropinput.h"

#include <QLabel>
#include <QLineEdit>

SvgPropInput::SvgPropInput(const QString& text, double max, double min, QWidget* parent)
	: QWidget(parent)
	, m_label(new QLabel(text, this))
	, m_edit(new QLineEdit(this))
	, m_max(max)
	, m_min(min)
{
	setFixedSize(75, 75);
	m_label->setGeometry(2, 0, 75, 20);
	m_edit->setGeometry(0, 20, 75, 55);
	m_edit->setValidator(new QDoubleValidator(min, max, 5, this));
	m_edit->setDisabled(true);

	m_edit->setStyleSheet(QStringLiteral(
		"font-size: 24px;background-color:rgb(236, 236, 238); border: 0px; margin: 0px; outline: 0px"));

	connect(m_edit, &QLineEdit::editingFinished, this, &SvgPropInput::_EditFinished);
}

void SvgPropInput::SetInc(double inc)
{
	m_inc = inc;
}

double SvgPropInput::Value() const
{
	return m_edit->text().toDouble();
}

void SvgPropInput::SetValue(double value)
{
	m_value = value;
	m_edit->setText(QString::number(int(value)));
}

void SvgPropInput::mousePressEvent(QMouseEvent* event)
{
	m_lastPoint = event->localPos();
	QWidget::mousePressEvent(event);
}

void SvgPropInput::mouseDoubleClickEvent(QMouseEvent* event)
{
	m_edit->setEnabled(true);
	QWidget::mouseDoubleClickEvent(event);
}

void SvgPropInput::mouseMoveEvent(QMouseEvent* event)
{
	if (event->buttons() & Qt::LeftButton)
	{
		if (event->localPos().y() < m_lastPoint.y() && m_value + m_inc < m_max)
		{
			m_value += m_inc;
			m_edit->setText(QString::number(static_cast<int>(m_value)));
			emit ValueChanged(m_value);
		}
		else if (event->localPos().y() > m_lastPoint.y() && m_value - m_inc > m_min)
		{
			m_value -= m_inc;
			m_edit->setText(QString::number(static_cast<int>(m_value)));
			emit ValueChanged(m_value);
		}
		m_lastPoint = event->localPos();
	}
	QWidget::mouseMoveEvent(event);
}

void SvgPropInput::mouseReleaseEvent(QMouseEvent* event)
{
	m_lastPoint = { NAN, NAN };
	QWidget::mouseReleaseEvent(event);
}

void SvgPropInput::focusOutEvent(QFocusEvent* event)
{
	m_edit->setDisabled(true);
	m_value = m_edit->text().toDouble();
	emit ValueChanged(m_value);
	QWidget::focusOutEvent(event);
}

void SvgPropInput::_EditFinished()
{
	m_edit->setDisabled(true);
	m_value = m_edit->text().toDouble();
	emit ValueChanged(m_value);
}
